/**
 * recmainthrd.c
 */

#include <pthread.h>

#include "avVidMainThrd.h"

#include "avRecMainThrd.h"

/**
 * process chnvid record
 * @param
 *		pChnVid	input	chnvid pointer
 */
static void procChnVidRec(ChnVid * pChnVid) 
{
	if (pChnVid->pParam->isVideo) 
	{
		char *pPriSec = pChnVid->primary ? "pri" : "sec";
			
		// alarm
		RecEnv *pAREnv = &pChnVid->almRecEnv;	//AR: alarm record
		pthread_mutex_lock(&pAREnv->lock);
		if (!pAREnv->recording && pAREnv->recParam.alarming) 
		{
			pAREnv->recording = true;
			CreateThread(&pAREnv->tid, recThrd, pAREnv);
			LOGINFO("chnvid %d %s will alarm recode %d seconds\n", pChnVid->id, pPriSec, pAREnv->recParam.seconds);
		}
		pthread_mutex_unlock(&pAREnv->lock);

		// scheme
		RecEnv *pSREnv = &pChnVid->schemeRecEnv;	// SR: scheme record
		pthread_mutex_lock(&pSREnv->lock);
		if (!pSREnv->recording && pSREnv->pCapturer != NULL &&
				isCurrInSchemeListRange(pSREnv->pCapturer->pSchemeList)) 
		{
			pSREnv->recording = true;
			pSREnv->recParam.seconds = getCurrContSec(pSREnv->pCapturer->pSchemeList);
			CreateThread(&pSREnv->tid, recThrd, pSREnv);
			LOGINFO("chnvid %d %s will scheme record %d seconds\n", pChnVid->id, pPriSec, pSREnv->recParam.seconds);
		}		
		pthread_mutex_unlock(&pSREnv->lock);
	}
}

void *recMainThrd(void *arg) 
{
	int i;

	LOGINFO("go to recMainThrd loop\n");
	while (!g_avEnv.quit) 
	{
		for (i = 0; i < CAPTURER_NUM; i++)
		{
			procChnVidRec(&g_avEnv.aPriChnVid[i]);
			procChnVidRec(&g_avEnv.aSecChnVid[i]);
		}
		usleep(1000 * 1000);	// 1000ms = 1s, sienr, 20100611
	}

	LOGINFO("recMainThrd end\n");
	return NULL;
}

